In this chapter, Mr. Ramalho discusses the Python Data Model. Framework here doesn't mean something like Django or Pyramid, but more about how language features and the core libraries fit together and the underlying philosphy that tie them together.
It reminded me a lot about when Josh Bloch talks about the Java Collections Framework.
In Java, you're expected to override or implement standard classes or interfaces to work with the framework. In Python, we implement the dunder methods such as getitem, which will then get called by the framework when we apply the [] operator to our class. Same goes for len, which gets called when people call len() on our class (by the way, the book has a great explanation on why len is not a method. Certainly something that at first seems to be inconsistent for someone coming from Java. If you haven't read the book, you really should).
Now for examples:
In [6]:
class DaysOfWeek:
def __init__(self):
self._days = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"]
def __getitem__(self, position):
return self._days[position]
def __len__(self):
return len(self._days)
days_of_week = DaysOfWeek()
"'{0}' is day number {1} of the {2} days.".format(days_of_week[1], 1, len(days_of_week))
Out[6]:
He talks about other dunder methods as well. In Java, Object's toString method is certainly one of the most well-known methods. In Python, this would be str and repr, two methods that are similar but have slightly different goals.
An example may make this clearer.
In [10]:
from datetime import timedelta
class Duration:
def __init__(self, milliseconds):
self._duration_in_milliseconds = milliseconds
def __repr__(self):
# return unambiguous string that mimics the source code to construct the object back
return "Duration({0})".format(self._duration_in_milliseconds)
def __str__(self):
return str(timedelta(milliseconds=self._duration_in_milliseconds))
a_billion_milliseconds = Duration(1_000_000_000)
"'{0}' is unambiguous, '{1}' is human-friendly".format(repr(a_billion_milliseconds), str(a_billion_milliseconds))
Out[10]:
There are many other dunder methods that we can implement of course. But time to move on to the next chapter.